package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.zadtek.shopmall.Event.EventUpdateAddressList;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.AddressItem;
import com.zadtek.shopmall.bean.CityBean;
import com.zadtek.shopmall.bean.JsonBean;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.other.AreaManger;
import com.zadtek.shopmall.utils.GetJsonDataUtil;
import com.zadtek.shopmall.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class EditAddressActivity extends AbsActivity {

    private EditText etAddressName;
    private EditText etAddressPhonenumber;
    private EditText etAddressArea;
    private EditText etAddressDetail;
    private TextView tvSave;
    private ImageView ivBack;
    private TextView topTitle;

    private AddressItem addressItem;

    private List<CityBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    @Override
    public int setView() {
        return R.layout.activity_edit_address;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        requestData();
    }

    private void requestData() {
        Intent intent = getIntent();
        AddressItem item = (AddressItem) intent.getSerializableExtra("addressitem");
        if(item!=null){
            addressItem = item;
        }else{
            addressItem = new AddressItem();
        }
        updateView();
        AreaManger.fetch(new AreaManger.OnArae() {
            @Override
            public void onFetch(List<CityBean> cityBeans) {
                initJsonData(cityBeans);
            }
        });
    }

    private void updateView() {
        etAddressName.setText(addressItem.getConsignee());
        etAddressPhonenumber.setText(addressItem.getMobile());
        etAddressArea.setText(addressItem.getArea());
        etAddressDetail.setText(addressItem.getAddress());
    }

    private void initLogic() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveAddress();
            }
        });
        etAddressArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerView();
            }
        });
    }

    private void saveAddress() {
        String name = etAddressName.getText().toString();
        String phonenumber = etAddressPhonenumber.getText().toString();
        String area = etAddressArea.getText().toString();
        String detail = etAddressDetail.getText().toString();
        if(TextUtils.isEmpty(name)||TextUtils.isEmpty(phonenumber)||TextUtils.isEmpty(area)||TextUtils.isEmpty(detail)){
            ToastUtil.showToast("请完善所有信息后提交！");
            return;
        }
        Map<String, Object> param = NetTool.newParams();
        if(addressItem.getAddress_id()!=0){
            param.put("address_id",addressItem.getAddress_id());
            param.put("type",1);
        }
        param.put("consignee",name);
        param.put("mobile",phonenumber);
        param.put("address",detail);
        param.put("province",addressItem.getProvince_id());
        param.put("city",addressItem.getCity_id());
        param.put("district",addressItem.getDistrict_id());
        NetTool.getApi().addAddress(param).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>(this) {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                ToastUtil.showToast("操作成功！");
                                EventBus.getDefault().post(new EventUpdateAddressList());
                                finish();
                            }else{
                                ToastUtil.showToast("操作失败！");
                            }
                        }
                    }
                });
        addressItem.setAddressArae(area);
        addressItem.setName(name);
        addressItem.setAddressDetail(detail);
        addressItem.setPhone(phonenumber);
    }

    private void initView() {
        etAddressName = (EditText)findViewById( R.id.et_address_name );
        etAddressPhonenumber = (EditText)findViewById( R.id.et_address_phonenumber );
        etAddressArea = (EditText)findViewById( R.id.et_address_area );
        etAddressDetail = (EditText)findViewById( R.id.et_address_detail );
        tvSave = (TextView)findViewById( R.id.tv_save );
        ivBack = (ImageView) findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        topTitle = (TextView) findViewById(R.id.title);
        topTitle.setText("新增地址");
    }

    private void initJsonData(List<CityBean> cityBeans) {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *

         * */
//        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
//
//        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = cityBeans;

        for (int i = 0; i < cityBeans.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < cityBeans.get(i).getSon().size(); c++) {//遍历该省份的所有城市
                String CityName = cityBeans.get(i).getSon().get(c).getRegion_name();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (cityBeans.get(i).getSon().get(c).getSon() == null
                        || cityBeans.get(i).getSon().get(c).getSon().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for(CityBean bean : cityBeans.get(i).getSon().get(c).getSon()){
                        City_AreaList.add(bean.getRegion_name());
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }
    private void showPickerView() {// 弹出选择器
        if(options1Items.size() == 0){
            ToastUtil.showToast("城市数据加载中！");
            return;
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                addressItem.setProvince_id(options1Items.get(options1).getRegion_id());
                addressItem.setCity_id(options1Items.get(options1).getSon().get(options2).getRegion_id());
                addressItem.setDistrict_id(options1Items.get(options1).getSon().get(options2).getSon().get(options3).getRegion_id());
                etAddressArea.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

}
